from threading import local
import threading
import time


# 当每个线程在执行 val.xx 时，
# threading.local()为每个线程都开辟了内存来存储 xx = 1
# val.xx 会找到此线程之间的内存地址去取之间存储的 xx

val1 = threading.local()


def task(i):
    val1.num = i
    time.sleep(1)
    print(val1.num)


for i in range(4):
    t = threading.Thread(target=task, args=(i,))
    t.start()


"""

所有线程只能操作一个num，打印出来的num一样

val1 = local()


class Foo:
    def __init__(self) -> None:
        self.num = 0


val2 = Foo()


def task(i):
    val2.num = i
    time.sleep(1)
    print(val2.num)


for i in range(4):
    t = threading.Thread(target=task, args=(i,))
    t.start()
"""
